import * as api from './api';
import {PAGE_CODE} from './constants';
import {PAGE} from '../constants';
import {
    getCurrentUserPagePermissionsSuccess,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsApi
} from 'Shared/actions/currentUserContext';
export const ERROR_CODE = 'error';
export const GET_INIT_DATA_BEGIN = 'GET_INIT_DATA_BEGIN';
export const GET_INIT_DATA_SUCCESS = 'GET_INIT_DATA_SUCCESS';
export const GET_INIT_DATA_FAIL = 'GET_INIT_DATA_FAIL';
import {conventTableCondition} from '../utils';
import moment from 'moment';
const getInitDataBegin = () => ({
    type: GET_INIT_DATA_BEGIN
});

const getInitDataSuccess = data => ({
    type: GET_INIT_DATA_SUCCESS,
    data
});
const getInitDataFail = () => ({
    type: GET_INIT_DATA_FAIL
});
/**初始化 */
/*==============================查询列表================================= */
export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';
export const getListBegin = () => ({
    type: GET_LIST_BEGIN
});
const getListSuccess = (condition, data) => ({
    type: GET_LIST_SUCCESS,
    condition,
    data
});
export const getListFail = () => ({
    type: GET_LIST_FAIL
});
/*==============================初始化API================================= */
//获取初始化数据和权限
export const getInitData = () => dispatch => {
    dispatch(getInitDataBegin());
    const init = api.getInitData().then(res => {
        if(res.ok)
            dispatch(getInitDataSuccess(res.data));
        else
            dispatch(getInitDataFail());
        return res.ok;
    });
    const permissions = getCurrentUserPagePermissionsApi(PAGE_CODE).then(res => {
        if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });

    return Promise.all([init, permissions]).then(values => values[0] && values[1]);
};

/*==============================查询action================================= */
//获取查询列表
const conventDate = (condition = {}) => {
    const {orderDate, ...others} = condition;
    if(!orderDate || orderDate.length === 0) return condition;
    return {
        ...others,
        beginOrderDate: moment(orderDate[0]).toISOString(),
        endOrderDate: moment(orderDate[1]).toISOString(),
    };
};
export const getList = condition => dispatch => {
    dispatch(getListBegin());
    const queryCondition = conventTableCondition(conventDate(condition));
    return api.getList(queryCondition).then(res => {
        if(res.ok)
            dispatch(getListSuccess(condition, res.data));
        else
            dispatch(getListFail());
    });
};

//修改查询条件
export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
//重置查询条件
export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});

//按钮搜索
export const querySearch = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryCondition']).toJS();
    const pageTableCondition = getState().getIn(['page', 'appState', 'queryBySort']).toJS();
    condition.pageSize = pageTableCondition.pageSize || PAGE.size;
    condition.sortedColumnKey = pageTableCondition.sortedColumnKey;
    condition.sortedOrder = pageTableCondition.sortedOrder;
    dispatch(getList(condition));
};
//分页排序搜索
export const tableSearch = page => (dispatch, getState) => {
    const query = getState().getIn(['page', 'appState', 'queryBySort']).toJS();
    if(!query.pageIndex || !page)
        query.pageIndex = 0;
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};

//选择查询条件
export const SAVE_QUERY_DEALER = 'SAVE_QUERY_DEALER';
export const saveQueryDealer = data => ({
    type: SAVE_QUERY_DEALER,
    data
});
//初始化搜索
import {partBackOrderDealStatus, partBackOrderStatus} from '../Enum';
export const initSearch = () => (dispatch, getState) => {
    const user = getState().getIn((['page', 'domainData', 'initData'])).toJS();
    if(!user.brands.length) {
        dispatch(getInitDataBegin());
        api.getInitData().then(res => {
            if(res.ok) {
                dispatch(getInitDataSuccess(res.data));
                if(res.data.isDealerUser) {
                    const listData = getState().getIn((['page', 'domainData', 'list', 'data'])).toJS();
                    const condition = getState().getIn(['page', 'appState', 'queryCondition']).toJS();
                    condition.pageSize = PAGE.size;
                    condition.status = partBackOrderStatus.新建;
                    if(listData.length < 1)
                        dispatch(getList(condition));
                }
            } else dispatch(getInitDataFail());
        });
    }
};
/*==============================确认action================================= */
export const onConfirmor = details => () => {
    const cancelCondition = details.map(v => ({
        id: v.id,
        partBackOrderId: v.partBackOrderId,
        cancelQuantity: v.dealStatus === partBackOrderDealStatus.申请取消 ? v.cancelQuantity : undefined,
        dealStatus: v.dealStatus === partBackOrderDealStatus.未处理 ? partBackOrderDealStatus.继续等待 : v.dealStatus,
        rowVersion: v.rowVersion,
    }));
    return api.confirmorData(cancelCondition).then(res => ({success: res.ok}));
};
/*==============================关闭action================================= */
export const onCloseSubmit = data => () => api.colseData(data).then(res => ({success: res.ok}));
/*==============================导出================================= */
export const exportData = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryCondition']).toJS();
    return api.exportPartIns(conventDate(condition));
};
/*==============================导入模板action================================= */
export const importApproveTemp = () => () => api.importApproveTemp();
export const importTemp = () => () => api.importTemp();
